Better Java method Syntax? Return early or late? [closed]

Posted by Gandalf on Stack Overflow See other posts from Stack Overflow or by Gandalf
Published on 2009-05-19T18:54:27Z Indexed on 2010/04/04 9:13 UTC
Read the original article Hit count: 305

Duplicate: Should a function have only one return statement? and Single return or multiple return statements?

Often times you might have a method that checks numerous conditions and returns a status (lets say boolean for now). Is it better to define a flag, set it during the method, and return it at the end :

boolean validate(DomainObject o) {
  boolean valid = false;
  if (o.property == x) {
     valid = true;
  } else if (o.property2 == y) {
     valid = true;
  } ...
  return valid; 
}

or is it better/more correct to simply return once you know the method's outcome?

boolean validate(DomainObject o) {

  if (o.property == x) {
     return true;
  } else if (o.property2 == y) {
     return true;
  } ...
  return false; 
}

Now obviously there could be try/catch blocks and all other kinds of conditions, but I think the concept is clear. Opinions?

© Stack Overflow or respective owner

Related posts about java

Related posts about coding-style